/**
 * Created by Micheal Xiao on 2017/12/15.
 */
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API, //http://xl.hantehulian.com  http://www.co-effort.com
  // timeout: 10000,                  // 请求超时时间
  params:{}
})


// service.defaults.headers.common['lang'] = store.state.headTitle.lang;
// request拦截器
service.interceptors.request.use(config => {
  try{
    config.params['number']=Math.random();
   }catch(e){
    config.params=new Object;
    config.params['number']=Math.random();
   }
   
  // Do something before request is sent
  var regEN = new RegExp(/en_/);
  var regCHS = new RegExp(/zh_/);
  var regJAN = new RegExp(/jap_/);
  if(regEN.test(window.location.href)){
    console.log('en')
    config.headers.common['lang'] = 'EN';
  }
  if(regCHS.test(window.location.href)){
    config.headers.common['lang'] = 'CHS';
  }
  if(regJAN.test(window.location.href)){
    config.headers.common['lang'] = 'JAP';
  }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    // store.commit('SET_NOTXHR')
    return response
  },
  error => {
    // store.commit('SET_NOTXHR')
    console.log('fetch ERR')
    console.log(error)

    if (typeof error.response.data.description === 'string') {
      Message({
        message: error.response.data.description,
        type: 'error',
      })
    } else {
      Message({
        message: error.response.data.description[0],
        type: 'error',
      })
    }

    // return Promise.reject(error)
  }
)

export default service
